package com.un.ebs.invoice.aspect;

import com.un.ebs.core.util.StringUtils;
import com.un.ebs.invoice.CostCode;
import com.un.ebs.invoice.domain.InvoiceCashNote;
import com.un.ebs.invoice.domain.InvoiceCashNoteExt;
import com.un.ebs.invoice.enums.InvoiceCashTypeEnum;
import com.un.ebs.invoice.service.InvoiceNoteService;
import com.un.ebs.sys.service.ConfigureService;
import com.un.ebs.sys.service.WxService;
import org.aspectj.lang.JoinPoint;
import org.aspectj.lang.annotation.AfterReturning;
import org.aspectj.lang.annotation.Aspect;
import org.springframework.stereotype.Component;

import javax.annotation.Resource;
import java.util.stream.Collectors;

/**
 * @author liubo
 * @email liubocs@163.com
 * @date 2020/12/6 22:31
 */
@Aspect
@Component
public class InvoiceNoteServiceAspect {

    @Resource
    private InvoiceNoteService invoiceNoteService;

    @Resource
    private ConfigureService configureService;

    @Resource
    private WxService wxService;

    @AfterReturning(value = "execution(* com.un.ebs.invoice.service.impl.InvoiceNoteServiceImpl.cash(String,Double,java.util.Date,com.un.ebs.invoice.enums.InvoiceCashTypeEnum,String))", returning = "cashNote")
    public void cash(JoinPoint joinPoint, InvoiceCashNote cashNote) {
        if (cashNote == null) {
            return;
        }
        if (cashNote.getCashType() != InvoiceCashTypeEnum.Collection) {
            return;
        }
        InvoiceCashNoteExt data = invoiceNoteService.queryCashViewById(cashNote.getId());
        for (String userId : invoiceNoteService.queryNotCash(cashNote.getEntId(), -1, 1).getRecords().stream().map(s -> s.getSubmitAt()).distinct().collect(Collectors.toList())) {
            send(userId, data);
        }
        send("9bddd1d360947dbd79a39499148a7645", data);

    }

    private void send(String userId, InvoiceCashNoteExt note) {
        String id = configureService.getValueByCode(CostCode.customer_invoice_cash_id);
        String config = configureService.getValueByCode(CostCode.customer_invoice_cash_config);
        String url = configureService.getValueByCode(CostCode.customer_invoice_cash_url);

        if (StringUtils.isNullOrEmpty(id) || StringUtils.isNullOrEmpty(config)) {
            return;
        }

        wxService.sendTemplateMessage(
                note.getTenantId(),
                "客户回款通知",
                userId,
                id,
                StringUtils.splitTemplate(config.split("~"), note),
                url
        );
    }
}
